package net.oschina.android.util;

import java.io.StringReader;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;
import android.content.Context;
import android.util.Log;
import com.android.volley.AuthFailureError;
import com.android.volley.NetworkResponse;
import com.android.volley.ParseError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.toolbox.HttpHeaderParser;

/**
 * @author HuangWenwei
 *
 * @date 2014年8月24日
 */
public class XmlRequest extends Request<XmlPullParser> {
	
	private final Listener<XmlPullParser>mListener;
	private Map<String, String>params;
	private Context context;

	/**
	 * @param method
	 * @param url
	 * @param listener
	 */
	public XmlRequest(Context context,int method, String url, Map<String, String>params, Listener<XmlPullParser>listener, 
			ErrorListener errorListener) {
		super(method, url,errorListener);
		this.mListener =listener;
		this.params = params;
		this.context = context;
	}
	
	/**
	 * @param url
	 * @param listener
	 * @param errorListener
	 */
	public XmlRequest(Context context,String url, Listener<XmlPullParser>listener, ErrorListener errorListener) {
		super(Method.GET,url, errorListener);
		this.mListener = listener;
		this.context = context;
	}

	@Override
	protected void deliverResponse(XmlPullParser response) {
		mListener.onResponse(response);
	}

	@Override
	public Map<String, String> getHeaders() throws AuthFailureError {
		Map<String, String> headers = new HashMap<>();
		if(!CacheUtil.getCookie(context.getApplicationContext()).equals(""))
			headers.put("Cookie", CacheUtil.getCookie(context.getApplicationContext()));
		return headers;
	}

	@Override
	protected Map<String, String> getParams() throws AuthFailureError {
		return params;
	}

	@Override
	protected Response<XmlPullParser> parseNetworkResponse(NetworkResponse response) {
		
		Map<String,String>headers = response.headers;
		if(headers.containsKey("Set-Cookie")){
			String cookie = headers.get("Set-Cookie");
			CacheUtil.saveCookie(context.getApplicationContext(), cookie);
		}
		
		try {
			String xmlString = new String(response.data,HttpHeaderParser.parseCharset(response.headers));
			XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
			XmlPullParser xmlPullParser = factory.newPullParser();
			xmlPullParser.setInput(new StringReader(xmlString));
			return Response.success(xmlPullParser,HttpHeaderParser.parseCacheHeaders(response));
		} catch (UnsupportedEncodingException e) {
			return Response.error(new ParseError(e));
		} catch (XmlPullParserException e) {
			return Response.error(new ParseError(e));
		}
	}
}
